﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using System.Collections.Generic;
using PowerCreator.LMS.Course.Entity;
using PowerCreator.LMS.Common.Utils;
using PowerCreator.LMS.Web.Course;
using PowerCreator.LMS.Web.Paper;
using PowerCreator.LMS.Paper.Entiry;
using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Web.Config;
using PowerCreator.LMS.Web.Project;
using PowerCreator.LMS.Project.Entity;

public partial class Theme_index_OpenCourse : PowerCreator.LMS.Web.Base.WebBasePage
{
    ManagerPaper opPaper = new ManagerPaper();
    NewProjectPlan opProjectPlan = new NewProjectPlan();

    PowerCreator.LMS.Web.Course.Course opCourse = new PowerCreator.LMS.Web.Course.Course();
    PowerCreator.LMS.Web.Catalog.Catalog opCatalog = new PowerCreator.LMS.Web.Catalog.Catalog();
    PowerCreator.LMS.Web.Course.Resource opResource = new PowerCreator.LMS.Web.Course.Resource();
    protected PowerCreator.LMS.Web.Config.WebConfig config = new PowerCreator.LMS.Web.Config.WebConfig();
    string _descriptionPaper = "试卷得分:";
    string _descriptionResource = "共学习{0}次,{1}";
    protected string CourseName = "";
    private PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();
    private string url = "UserLogin.aspx";
    protected string courseID = "0";
    protected string classID = "0";
    protected string teacherid = "0";
    private double coursePeriod = 0;
    private int myTotalPeriod = 0;
   
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckUser();
        login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
        ViewState["ClassID"] = 0;
        ViewState["CourseID"] = 0;
        ViewState["RestpID"] = 0;
        if (Request.QueryString["CourseID"] != null)
        {
            courseID = Request.QueryString["CourseID"].ToString();
            ViewState["CourseID"] = courseID;
            if (Request.QueryString["ClassID"] != null)
            {

                classID = Request.QueryString["ClassID"].ToString();
                ViewState["ClassID"] = classID;
            }
            GetThisCourse(int.Parse(courseID));
            GetCoursePeriod(courseID, classID);
            GetMyTotalPeriod(courseID, classID);
            BinderCourseResourceType(courseID);
            //if (myTotalPeriod >= coursePeriod)
            //    td_exam.Visible = true;
            //else
            //    td_exam.Visible = false;
        }
    }


    private void CheckUser()
    {
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
        {
            Script.RedirectURL(url);
        }

        login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
        if (login == null)
        {
            Script.RedirectURL(url);
        }

    }
    private void GetThisCourse(int cid)
    {
        PowerCreator.LMS.Course.Entity.VOTOCourse vo = opCourse.LoadVOTCourse(cid);
        //lbl_CourseImage.Text = "<img alt=\"mc\" src=\"" + vo.CourseImgUrl + "\"  class=\"imgstyle\" width=\"280\" height=\"280\" />";
        lbl_CourseName.Text = vo.CourseName;
        teacherid = vo.FKCourseMostlyTeacherID.ToString();

        //CourseName = vo.CourseName;
        //this.Title = CourseName;
        //lbl_Teacher.Text = vo.CourseMostlyTeacherName;
        //lbl_CoursePeriod.Text = vo.CoursePeriod.ToString();
        //lbl_Description.Text = vo.Description;
        //lbl_CourseName2.Text = vo.CourseName;
    }
    private void GetCoursePeriod(string couid, string claid)
    {
        string bid="0";
        PowerCreator.LMS.ViewQuery.ViewQuery obj = new PowerCreator.LMS.ViewQuery.ViewQuery();
        string sql = "SELECT TO_Batch.Batch_Id FROM TO_CourseList INNER JOIN TO_Batch ON TO_CourseList.Batch_Id = TO_Batch.Batch_Id INNER JOIN  TO_Class ON  TO_CourseList.CourseList_Id = TO_Class.ClassCourseListID where TO_Class.Class_Id=" + claid;
        DataTable dt = new DataTable();
        dt = obj.Query(sql);
        if (dt.Rows.Count > 0)
            bid = dt.Rows[0]["Batch_Id"].ToString();
        sql = "SELECT TO_FormulaOfRule.TotalTime_Low FROM TO_Rule INNER JOIN TO_FormulaOfRule ON TO_Rule.Rule_Id = TO_FormulaOfRule.RuleID where TO_Rule.FKBatchID="+bid+" and TO_Rule.FKCourseID="+couid;
        dt.Clear();
        dt = obj.Query(sql);
        if (dt.Rows.Count > 0)
            coursePeriod = double.Parse(dt.Rows[0]["TotalTime_Low"].ToString());
    }
    private void GetMyTotalPeriod(string couid, string claid)
    {
        int totaltime = 0;
        PowerCreator.LMS.ViewQuery.ViewQuery obj = new PowerCreator.LMS.ViewQuery.ViewQuery();
        string sql = "select sum(SscrlogTotalTime) as TotalPeriod from TStudentStudyCouReslog where   FKSscrlogCourseID=" + couid + " and FKSscrlogTrainclaID=" + claid + "";
        DataTable dt = new DataTable();
        dt = obj.Query(sql);
        if (dt.Rows.Count > 0)
        {
            if (dt.Rows[0]["TotalPeriod"].ToString().Length > 0)
                totaltime = int.Parse(dt.Rows[0]["TotalPeriod"].ToString());
        }
        myTotalPeriod = totaltime / 3600;        
    }
    private void BinderCourseResourceType(string cid)
    {
        //UserStowResource opUserStowResource = new UserStowResource();
        string search = " RestpID in (select FKCoursersRestpID from TCourseResource where FKCourseresCourseID="+cid+")";
        DataTable dt = opCourse.QueryResourceType(search);

        rptResourceType_01.DataSource = dt;
        rptResourceType_01.DataBind();
        //rptResourceType_02.DataSource = dt;
        //rptResourceType_02.DataBind();
        

    }
    protected void rpt_ResourceList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "stow")
        {
            if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
            {
                PowerCreator.LMS.Common.Script.Script.Alert(config.GetLanagerValueByKey("theme_Channel_LoginMsg", PowerCreator.LMS.Language.LanagetItemType.Page));
                return;
            }
            PowerCreator.LMS.Web.User.LoginEntity login = (PowerCreator.LMS.Web.User.LoginEntity)Session[WebConfig.SESSION_USER_USERINFO];
            if (login == null)
            {
                PowerCreator.LMS.Common.Script.Script.Alert(config.GetLanagerValueByKey("theme_Channel_LoginMsg", PowerCreator.LMS.Language.LanagetItemType.Page));
                return;
            }

            VOTCourseResource vo = opCourse.LoadCourseResource(int.Parse(e.CommandArgument.ToString()));
            PowerCreator.LMS.Course.Entity.VOTUserStowResource voUserStowResource = new VOTUserStowResource();
            UserStowResource op = new UserStowResource();
            voUserStowResource.FKResourceID = vo.FKCoursersResourceID;
            voUserStowResource.FKUserID = login.UserID;
            voUserStowResource.CreateTime = DateTime.Now;
            voUserStowResource.DelFlag = 0;
            //if (op.AddUserStowResource(voUserStowResource))
            //{
            //    Button lbtn_Stow = (Button)e.Item.FindControl("lbtn_Stow");
            //    lbtn_Stow.Enabled = false;
            //}

        }

    }

    //DataTable为多表联链接查询后的数据
    private List<CourseResourceInfo> FillList(DataTable dt)
    {
        PowerCreator.LMS.ViewQuery.ViewQuery vo = new PowerCreator.LMS.ViewQuery.ViewQuery();

        login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
        string sql = string.Empty;
        int studytime = 0;
        string position = "0";
        DataTable dt01 = new DataTable();
        List<CourseResourceInfo> list = new List<CourseResourceInfo>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            CourseResourceInfo item = new CourseResourceInfo();
            item.CourseID = int.Parse(ViewState["CourseID"].ToString());
            item.CourseresID = int.Parse(dt.Rows[i]["CourseresID"].ToString());
            item.CoursersRestpID = int.Parse(dt.Rows[i]["FKCoursersRestpID"].ToString());

            VOTResourceType voResourceType = opCourse.LoadResourceType(item.CoursersRestpID);
            item.CoursersRestpName = voResourceType.RestpName;
            item.CoursersClassID = int.Parse(dt.Rows[i]["CoursersClass"].ToString());
            item.CoursersClassName = opCourse.GetCoursersClassByData(item.CoursersClassID, GetLanageValueByKey("Resource_Class1", PowerCreator.LMS.Language.LanagetItemType.Page), GetLanageValueByKey("Resource_Class2", PowerCreator.LMS.Language.LanagetItemType.Page));

            if (item.CoursersClassID == Convert.ToInt16(CoursersClass.Courseware))  //课件资源
            {
                item.CoursersResourceID = int.Parse(dt.Rows[i]["FKCoursersResourceID"].ToString());
                VOTResource voResource = opCourse.LoadResource(item.CoursersResourceID);
                item.ResourceName = voResource.ResourceName;
                item.CoursersResourceAuthor = voResource.ResourceAuthor;
                item.CoursersResourceDescription = voResource.ResourceDescription;
                item.CoursersResourceUrl = GetPath(voResource.ResourceUrl, voResource.ResourceClass);
                item.CoursersResourceImageUrl = item.CoursersResourceUrl + GetPicName(voResource.ResourceEntry, voResource.ResourceClass);
                if (login != null)
                {
                    //studytime = 0;
                    position = "0";
                    //sql = "Select SscrlogID  from TStudentStudyCouReslog where FKSscrlogUserID=" + login.UserID.ToString() + " and FKSscrlogCourseID=" + ViewState["CourseID"].ToString() + " and FKSscrlogTrainclaID=" + ViewState["ClassID"].ToString() + " and FKSscrlogResourceID=" + voResource.ResourceID.ToString() + "";
                    //studytime = vo.Count(sql);
                    //if (studytime > 0)
                    //{
                    //    sql = "Select sum(SscrlogTotalTime) as SscrlogTotalTime from TStudentStudyCouReslog where FKSscrlogUserID=" + login.UserID.ToString() + " and FKSscrlogCourseID=" + ViewState["CourseID"].ToString() + " and FKSscrlogTrainclaID=" + ViewState["ClassID"].ToString() + " and FKSscrlogResourceID=" + voResource.ResourceID.ToString() + "";
                    //    dt01 = vo.Query(sql);
                    //    if (dt01.Rows.Count == 1)
                    //        item.StudentPlanValue = string.Format(_descriptionResource, studytime.ToString(), PowerCreator.LMS.Common.Utils.TimeUtils.GetTimeStrShort(dt01.Rows[0]["SscrlogTotalTime"].ToString()));
                    //    else
                    //        item.StudentPlanValue = string.Format(_descriptionResource, studytime.ToString(), "");
                    //    sql = "Select top 1 SscrlogCurrentPosition from TStudentStudyCouReslog where FKSscrlogUserID=" + login.UserID.ToString() + " and FKSscrlogCourseID=" + ViewState["CourseID"].ToString() + " and FKSscrlogTrainclaID=" + ViewState["ClassID"].ToString() + " and FKSscrlogResourceID=" + voResource.ResourceID.ToString() + " order by SscrlogID desc";
                    //    dt01 = vo.Query(sql);
                    //    if (dt01.Rows.Count > 0)
                    //    {
                    //        position = dt01.Rows[0]["SscrlogCurrentPosition"].ToString();
                    //    }
                    //}
                    //else
                    //    item.StudentPlanValue = string.Format(_descriptionResource, studytime.ToString(), "");


                    sql = "Select top 1 SscrlogCurrentPosition from TStudentStudyCouReslog where FKSscrlogUserID=" + login.UserID.ToString() + " and FKSscrlogCourseID=" + ViewState["CourseID"].ToString() + " and FKSscrlogTrainclaID=" + ViewState["ClassID"].ToString() + " and FKSscrlogResourceID=" + voResource.ResourceID.ToString() + " order by SscrlogID desc";
                    dt01 = vo.Query(sql);
                    if (dt01.Rows.Count > 0)
                    {
                        position = dt01.Rows[0]["SscrlogCurrentPosition"].ToString();
                    }


                }
                //此处为打开课件的URL，为不在修改类库，此处用其代替，只在此文件与OpenCourseWareCommentNew.aspx中如此使用）
                item.CoursersResourceEntry = " href=\"OpenCourseware.aspx?ResourceID=" + voResource.ResourceID.ToString() + "&CourseResourceID=" + item.CourseresID + "&ClassID=" + ViewState["ClassID"].ToString() + "&Position=" + position + "&CourseID=" + item.CourseID.ToString() + "\" target=\"_blank\"";
            }
            else if (item.CoursersClassID == Convert.ToInt16(CoursersClass.Paper)) //试卷资源
            {
                item.CoursersResourceID = int.Parse(dt.Rows[i]["FKCoursersPaperID"].ToString());
                VOPaper voPaper = opPaper.LoadPaper(item.CoursersResourceID);
                item.ResourceName = voPaper.PaperName;
                item.CoursersResourceDescription = voPaper.PaperName;
                item.CoursersResourceUrl = "";
                item.CoursersResourceImageUrl = "images/Exam.jpg";

                if (login != null)
                {

                    PowerCreator.LMS.Web.Paper.ManagerPaper objManagerPaper = new ManagerPaper();
                    string search = " FKUPHistoryUserID=" + login.UserID.ToString() + " and FKUPHistoryCourseID=" + item.CoursersResourceID.ToString() + " and FKUPHistoryPaperID=" + dt.Rows[i]["FKCoursersPaperID"].ToString();

                    DataTable dt_UserPaperHistory = objManagerPaper.QueryUserPaperHistory(search);
                    if (dt_UserPaperHistory.Rows.Count != 0)
                    {
                        string readState = dt_UserPaperHistory.Rows[0]["UPHistoryReadState"].ToString();
                        string SubmitTime = dt_UserPaperHistory.Rows[0]["UPHistorySubmitTime"].ToString().Trim();
                        if (readState == "1")
                            //此处为打开课件的URL，为不在修改类库，此处用其代替，只在此文件与OpenCourseWareCommentNew.aspx中如此使用）
                            item.CoursersResourceEntry = " href=\"" + WebUtils.WebRoot + "/web/UserObject/ReadedPaper.aspx?PaperID=" + voPaper.PaperID.ToString() + "&ProjectID=0&ClassID=" + ViewState["ClassID"].ToString() + "&CourseID=" + item.CourseID.ToString() + "&UserID=" + login.UserID.ToString() + "\" target=\"_blank\"";
                        else if (readState == "0" && SubmitTime == "")
                            //此处为打开课件的URL，为不在修改类库，此处用其代替，只在此文件与OpenCourseWareCommentNew.aspx中如此使用）
                            item.CoursersResourceEntry = " href=\"" + WebUtils.WebRoot + "/web/UserObject/OpenPaperList.aspx?ResourceID=" + voPaper.PaperID.ToString() + "&ProjectID=0&ProjectClassID=" + ViewState["ClassID"].ToString() + "&IsBuKao=0&ProjectResourceID=0&CourseResourceID=0&CourseID=" + item.CourseID.ToString() + "\" target=\"_blank\"";
                        else
                        {
                            item.CoursersResourceEntry = "#";
                            item.CoursersResourceMsg = config.GetLanagerValueByKey("theme_Paper_ExamMsg", PowerCreator.LMS.Language.LanagetItemType.Page);
                        }

                    }
                    else
                        //此处为打开课件的URL，为不在修改类库，此处用其代替，只在此文件与OpenCourseWareCommentNew.aspx中如此使用）
                        item.CoursersResourceEntry = " href=\"" + WebUtils.WebRoot + "/web/UserObject/OpenPaperList.aspx?ResourceID=" + voPaper.PaperID.ToString() + "&ProjectID=0&ProjectClassID=" + ViewState["ClassID"].ToString() + "&IsBuKao=0&ProjectResourceID=0&CourseResourceID=0&CourseID=" + item.CourseID.ToString() + "\" target=\"_blank\"";
                }
                else
                {
                    item.CoursersResourceEntry = "#";
                    item.CoursersResourceMsg = config.GetLanagerValueByKey("theme_Channel_LoginMsg", PowerCreator.LMS.Language.LanagetItemType.Page);

                }
            }
            list.Add(item);
        }
        return list;
    }
    private string GetPicName(string fileName, int Resourceclass)
    {
        string rt = "images/Exam.jpg";
        if (Resourceclass == 1)
        {
            rt = "000.jpg";
        }
        else if (Resourceclass == 2)
        {
            string[] fileNames = fileName.Split('.');
            if (fileNames.Length == 2)
                rt = fileNames[0].ToString() + ".jpg";
        }
        return rt;
    }
    private string GetPath(string Path, int Resourceclass)
    {
        string rt = Path;
        if (Resourceclass != 1 && Resourceclass != 2)
        {
            rt = "";
        }
        return rt;
    }



}
